import 'package:chat_message/models/chat_message.dart';
import 'package:chatgpt_flutter/util/conversation_context_helper.dart';
import 'package:chatgpt_flutter/util/hi_const.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:tyqw_flutter/core/ai_completions.dart';
import 'package:tyqw_flutter/utils/ai_logger.dart';
import 'package:wxyy_flutter/core/ai_completions.dart';
import 'package:wxyy_flutter/model/ai_send.dart';

class CompletionDao {
  final IConversationContext conversationContextHelper =   ConversationContextHelper();

  ///初始化会话上下文
  CompletionDao({List<MessageModel>? messages}) {
    MessageModel? question, answer;
    messages?.forEach((model) {
      //sender为提问者，receiver为ChatGPT
      if (model.ownerType == OwnerType.sender) {
        question = model;
      } else {
        answer = model;
      }
      if (question != null && answer != null) {
        conversationContextHelper
            .add(ConversationModel(question!.content, answer!.content));
        question = answer = null;
      }
    });
    AILogger.log(
        'init finish,prompt is ${conversationContextHelper.getPromptContext("")}');
  }

  // 和gpt进行会话
  Future<String?> createCompletions({required String prompt}) async {
    // 带有完整上下文信息的
    String fullPrompt = conversationContextHelper.getPromptContext(prompt);

    var model = HiCache.getInstance().get(HiConst.selectModel);
    model ??= HiConst.selectModel;
    var response;
    var choices;
    var content;
    if(model == 'qwen-turbo' || model == 'qwen-plus'){
      response = await TYQW_AICompletion().createChat(model: model ,prompt: fullPrompt);
      choices = response.output?.choices?.first;
      content = choices?.message?.content;
    } else{
      MessageWxyy messageWxyy = conversationMessageWx(fullPrompt);
      response = await WXYY_AICompletion().createChat(messages: messageWxyy);
      choices = response.result;
      content = choices;
    }
    debugPrint('content:$content');
    if (content != null) {
      var list = content.split('A:'); //过滤掉不想展示的字符
      content = list.length > 1 ? list[1] : content;
      content = content.replaceFirst("\n\n", ""); //过滤掉开始的换行
      conversationContextHelper.add(ConversationModel(prompt, content));
    }
    return content;
  }

  MessageWxyy conversationMessageWx(String fullPrompt) {
    List<String> qaList;
    if(fullPrompt.substring(0, 1) == "\n"){
      qaList = fullPrompt.substring(1).split('\n');
    }else{
      qaList = fullPrompt.split('\n');
    }
    List<MessageWx> messageWxList = <MessageWx>[];
    for(int i = 0; i< qaList.length; i++){
      if(i % 2 == 0){
        messageWxList.add(MessageWx(role: "user", content: qaList[i].substring(2, qaList[i].length)));
      }else{
        messageWxList.add(MessageWx(role: "assistant", content: qaList[i].substring(2, qaList[i].length)));
      }
    }
    return MessageWxyy(messages: messageWxList);
  }
}